const jwt = require("jsonwebtoken");
const { createUser, getUserInfo } = require("../service/user.service");
const { sendEmail, getNum, setNum } = require("../utils/mailAotu");
const { JWT_SECRET } = require("../config/config.default");
class UserController {
  //注册
  async register(ctx, next) {
    const { userEmail, password } = ctx.request.body;
    const num = getNum();
    const res = await createUser(userEmail, password);
    ctx.body = {
      code: 0,
      message: "用户注册成功",
      data: {
        userEmail: res.userEmail,
        userName: res.userName,
        userId: res.id,
      },
    };
  }
  //发送邮件
  async snedEmail(ctx, next) {
    const { userEmail } = ctx.request.body;
    const num = setNum();
    const res = await sendEmail(userEmail, num);
    if (!res) {
      ctx.body = {
        code: 10003,
        message: "邮件发送错误",
        data: "",
      };
      return;
    }
    ctx.state.num = 456;
    ctx.body = {
      code: 0,
      message: "邮件已发送",
      data: "",
    };
  }
  //d登录
  async login(ctx, next) {
    const { userEmail } = ctx.request.body;
    const { password, ...resUser } = await getUserInfo({ userEmail });
    ctx.body = {
      code: 0,
      message: "登录成功",
      data: {
        token: jwt.sign(resUser, JWT_SECRET, { expiresIn: "10d" }),
      },
    };
  }
  //获取用户信息
  async getUserInfo(ctx, next) {
    const { exp, iat, ...user } = ctx.state.user;
    ctx.body = {
      code: 0,
      message: "success o",
      data: user,
    };
  }
  
}

module.exports = new UserController();
